package com.coder.bike.controller;

import com.coder.bike.utils.HttpUtils;
import com.coder.bike.utils.RedisUtils;
import com.coder.bike.utils.Result;
import jakarta.annotation.Resource;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("sms")
@CrossOrigin
public class SMSController {

    @Resource
    private RedisUtils redisUtils;

    /**
     * 发送短信验证码
     * @param phoneNumber 手机号
     * @param type 验证码类型(login/register)
     * @return 发送结果
     */
    @GetMapping("send/{phoneNumber}/{type}")
    public Result sendCode(@PathVariable String phoneNumber, @PathVariable String type) {
        // 验证手机号格式
        if (!phoneNumber.matches("^1[3-9]\\d{9}$")) {
            return Result.fail().setMessage("手机号格式不正确");
        }

        // 检查发送频率(60秒内只能发送一次)
        String frequencyKey = "sms:frequency:" + phoneNumber;
        if (redisUtils.get(frequencyKey) != null) {
            return Result.fail().setMessage("操作过于频繁，请稍后再试");
        }

        // 生成6位随机验证码
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }

        // 存储验证码到Redis，有效期5分钟
        redisUtils.set("sms:code:" + type + ":" + phoneNumber, code.toString(), 300L);
        // 设置频率限制，60秒内不能重复发送
        redisUtils.set(frequencyKey, "1", 60L);
        System.out.println("验证码:" + code);
//        return Result.success().setMessage("验证码发送成功");
        // 调用短信服务API
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "447f55fbba59442bb96cc2ba2a7567cd";

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("content", "code:"+code);
        bodys.put("template_id", "CST_ptdie100");
        bodys.put("phone_number", phoneNumber);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String responseBody = EntityUtils.toString(response.getEntity());
            return Result.success().setMessage("验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().setMessage("验证码发送失败");
        }
    }


    @PostMapping("verify/{phoneNumber}/{type}")
    public Result verifyCode(@PathVariable String phoneNumber,
                             @PathVariable String type,
                             @RequestBody Map<String, String> requestBody) {  // 改为使用 @RequestBody
        String code = requestBody.get("code");

        if (code == null || code.isEmpty()) {
            return Result.fail().setMessage("验证码不能为空");
        }

        String key = "sms:code:" + type + ":" + phoneNumber;
        String correctCode = redisUtils.get(key);

        if (correctCode == null) {
            return Result.fail().setMessage("验证码已过期");
        }

        if (!correctCode.equals(code)) {
            return Result.fail().setMessage("验证码不正确");
        } else {
            redisUtils.del(key);
            return Result.success().setMessage("验证成功");
        }
    }
}